<?php
/**
 * 支付宝wap手机支付控制器
 */
namespace Mobile\Controller;
use Think\Controller;
include_once VENDOR_PATH.'alipaysdk/AopSdk.php';
class PayaliwapController extends Controller
{

    public $api_url = 'https://mapi.alipay.com/gateway.do?';
    public $ALIPAY_PAYKEY = 'e6js2ld2w548yhqergz1d9rp3gy6ejzk';
    public $partner = '2088231536595748';
    public $aop;
    public function __construct()
    {
        parent::__construct();
        $aop = new \AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2018090361266201';
        $aop->rsaPrivateKey = 'MIIEogIBAAKCAQEA0Ogm/rsCOs7KltzS/ZMXMMd3/3bn/VDxt8ilYZzkJBFC9kMjrsHXbhvjLYAr+qeiLqCgdkc++R48bNCS5eEiTbG846nEnc4tNJWmH16RzDJHkfShphQg8ht651jY8WzFj8NtR6cpKdh/Qmyb7RAXBvkErKcFpOvcbrDBSZoAj6SlfgaCVa5Iwo3BTt56tgSdm2BUImqLnfZbjhVl1pwkEu2qhX6vU8vMvFDOVdxcXw517vnTXqbsRkwfqynuQy+LQzMwXUjOTIUVcjfBq+rJCjnvklJgy9uZncriMOLoARsXx1jJoLmhxlIvQuMcd2ksk1W3NPldGthHPT1yOdqM+wIDAQABAoIBAB/ruTmnHZoayv3uVBcHCL4dXIqegqhEXAr3D74wmPOh55d1fthPKjna7QWg1heA0dlKFfq8vDSYmCcQX8Hcer9gbzpiUHbEcEferfmRG7oV3LXCqYiU/su/wzHic5PASRfEhsgyFKoeOKPPsKuyj7IzDrHK+6PNnmsTexViAL/x4+NjiEGEY4XiLh1L8mFr+xvm4+tfLuXrnt3eWJ9fsffJNvT3UUSsYu3dPr6momE4S/bZvwMnSsI4hnYbVhR8Hg51yfHp/ViRABQnaVMv1niRLA6znpYPubSbT3zEP/dMmOtaekLNNA81OZiLsF+q6CkIC9EjAgpnI5WEzQZFE0ECgYEA53d8NH6laFdr7fpQ3rAfVyyAoVDAWUtejRzvk/yK990AhMO3uXhMLxzyS72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y+Wmu6j38ndeuxLgfUyd4UpxC9eQtuJ+KaScFD8umxvJQd7+sqAYggB6jbhMrJ1dhJQBgGwztxAJMWOjOol0xg2trjOI0pz+Xlh/gjfunj8pcUHLpzN/aRl1GzLxu7kEIdoD2KL2Kjiczs5xte2JwIDAQAB';
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='utf-8';
        $aop->format='json';
        $this->aop = $aop;
    }

    public function wappay($data){
        
        $data['service'] = 'alipay.wap.create.direct.pay.by.user';
        $data['partner'] = $this->partner;//支付宝合作者身份ID 2088开头
        $data['seller_id'] = $data['partner'];//卖家支付宝账号
        $data['_input_charset'] = 'utf-8';
        $data['payment_type'] = '1';//1商品购买
        
//         取值范围：1m～15d。
//         m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。
//         该参数数值不接受小数点，如1.5h，可转换为90m。
//         当用户输入支付密码、点击确认付款后（即创建支付宝交易后）开始计时。
//         支持绝对超时时间，格式为yyyy-MM-dd HH:mm。
       //$data['it_b_pay'] = '3d';//选填,超时时间设置未付款交易的超时时间，一旦超时，该笔交易就会自动被关闭。

       // $data['rn_check'] = 'F';//是否发起实名校验T：发起实名校验； F：不发起实名校验。
        //买家证件号码（需要与支付宝实名认证时所填写的证件号码一致）。当scene=ZJCZTJF的情况下，才会校验buyer_cert_no字段。
       // $data['buyer_cert_no'] = '';//	
       // $data['buyer_real_name'] = '';//当scene=ZJCZTJF的情况下，才会校验buyer_real_name字段。
       // $data['scene'] = 'ZJCZTJF';//收单场景。如需使用该字段，需向支付宝申请开通，否则传入无效。
        
        
        //$data['goods_type'] = '0';//	商品类型。1：实物类商品0：虚拟类商品 不传默认为实物类商品。
        
        //app_pay=Y：尝试唤起支付宝客户端进行支付，若用户未安装支付宝，则继续使用wap收银台进行支付。
        //商户若为APP，则需在APP的webview中增加alipays协议处理逻辑。商户若为APP，则需在APP的webview中增加alipays协议处理逻辑。
        
        $data['app_pay'] = 'Y';//
        
        $data['sign'] = $this->_getSign($data);
        $data['sign_type'] = 'MD5';//DSA、RSA、MD5三个值可选，必须大写。
        
        $params = http_build_query($data);
        $api_url = $this->api_url.$params;
        
        return $api_url;
        
    }

    
    /**
     * 	作用：生成签名
     */
    protected function _getSign($Obj)
    {
        //过滤参数
        $Obj = $this->_paraFilter($Obj);
        
        foreach ($Obj as $k => $v)
        {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        
        $String = $this->_createLinkstring($Parameters);

        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
    
        $String = $String.$this->ALIPAY_PAYKEY;
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密

        $String = md5($String);

        return $String;
    }
    
    /**
     * 除去数组中的空值和签名参数
     * @param $para 签名参数组
     * return 去掉空值与签名参数后的新签名参数组
     */
    protected function _paraFilter($para) {
        $para_filter = array();
        while (list ($key, $val) = each ($para)) {
            if($key == "sign" || $key == "sign_type" || $val == "")continue;
            else	$para_filter[$key] = $para[$key];
        }
        return $para_filter;
    }
    
    
    /**
     * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param $para 需要拼接的数组
     * return 拼接完成以后的字符串
     */
    protected function _createLinkstring($para) {
    	$arg  = "";
    	while (list ($key, $val) = each ($para)) {
    		$arg.=$key."=".$val."&";
    	}
    	//去掉最后一个&字符
    	$arg = substr($arg,0,count($arg)-2);
    	
    	//如果存在转义字符，那么去掉转义
    	if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
    	
    	return $arg;
    }
    
    
    /*
     * 验证回调的真实性
     */
    public function checkSign($data){
        
        if(empty($data)) {//判断POST来的数组是否为空
            return false;
        }
        
        $sign = $this->_getSign($data);
        $post_sign = $data["sign"];
        if($sign == $post_sign){
            return true;
        }
        
        return false;
    }
    

    public function tradeWapPay ($order) {
        $aop = $this->aop;
        $request = new \AlipayTradeWapPayRequest ();

        $order_id = $order['order_id'];
        $request->setNotifyUrl(get_domain().'/mobile/ordercallback/newalipaycallback/order_id/'.$order_id);
        $request->setReturnUrl(get_domain().'/mobile/orderdetail/index/order_id/'.$order_id);

        $arr = array(
            'body' => $order['order_title'].$order['order_sn'],
            'subject' => $order['order_title'],
            'out_trade_no' => $order['order_sn'],
            'total_amount' => $order['pay_money'],
            'seller_id' => '',
            'quit_url' => get_domain().'/mobile/orderdetail?order_id='.$order['order_id'],
            'product_code' => 'QUICK_WAP_WAY',
        );
        
        $json = json_encode($arr);
        $request->setBizContent($json);
        $result = $aop->pageExecute($request); 
        _pr($result);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
        echo "成功";
        } else {
        echo "失败";
        }
    }

    public function tradeAppPay ($order) {
        $aop = $this->aop;
        $request = new \AlipayTradeAppPayRequest ();
        $order_id = $order['order_id'];
        $request->setNotifyUrl(get_domain().'/mobile/ordercallback/newalipaycallback/order_id/'.$order_id);
        $arr = array(
            'body' => $order['order_title'].$order['order_sn'],
            'subject' => $order['order_title'],
            'out_trade_no' => $order['order_sn'],
            'total_amount' => $order['pay_money'],
            'seller_id' => '',
            'product_code' => 'QUICK_MSECURITY_PAY',
        );
        $json = json_encode($arr);
        $request->setBizContent($json);
        $result = $aop->sdkExecute ( $request); 
        return $result;
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
        echo "成功";
        } else {
        echo "失败";
        }
    }

    function check($arr){
        /* $aop = $this->aop;
        $result = $aop->rsaCheckV1($arr, $aop->alipayrsaPublicKey, $aop->signType);
        return $result; */
        $res = $this->tradeQuery($arr['out_trade_no']);
        if($res&&$res['alipay_trade_query_response']['code']=='10000'&&$res['alipay_trade_query_response']['trade_status']=='TRADE_SUCCESS') {
            return true;
        }
        return false;
    }
    
    public function tradeQuery ($outtradeno) {
        $aop = $this->aop;
        $request = new \AlipayTradeQueryRequest ();
        $arr = array(
            'out_trade_no' => $outtradeno
        );
        $json = json_encode($arr);
        $request->setBizContent($json);
        $result = $aop->execute($request); 
        
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            $result = json_decode(json_encode($result),true);
            return $result;
        } else {
           return false;
        }
    }
    
}
